package cn.net.shuxing.yifu.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

public class MailUtil {

    public static boolean sendMail(String receiveMail, String code)
    {
        // 如果是除杭州region外的其它region（如新加坡、澳洲Region），需要将下面的"cn-hangzhou"替换为"ap-southeast-1"、或"ap-southeast-2"。
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAIQb8xLiRdju3q", "1G6AFqff9UyONRy8zroKpu8UZjfnZj");
        //使用https加密连接
        //profile.getHttpClientConfig().setProtocolType(com.aliyuncs.http.ProtocolType.HTTPS);
        // 如果是除杭州region外的其它region（如新加坡region）， 需要做如下处理
        //try {
        //DefaultProfile.addEndpoint("dm.ap-southeast-1.aliyuncs.com", "ap-southeast-1", "Dm",  "dm.ap-southeast-1.aliyuncs.com");
        //} catch (ClientException e) {
        //e.printStackTrace();
        //}
        IAcsClient client = new DefaultAcsClient(profile);
        SingleSendMailRequest request = new SingleSendMailRequest();
        try {
            //request.setVersion("2017-06-22");// 如果是除杭州region外的其它region（如新加坡region）,必须指定为2017-06-22
            request.setAccountName("yifu@register.zjyifu.vip");
            request.setFromAlias("壹付");
            request.setAddressType(1);
            request.setTagName("register");
            request.setReplyToAddress(true);
            request.setToAddress(receiveMail);
            //可以给多个收件人发送邮件，收件人之间用逗号分开，批量发信建议使用BatchSendMailRequest方式
            //request.setToAddress("邮箱1,邮箱2");
            request.setSubject("壹付邮箱认证");
            request.setHtmlBody("<html>\n" +
                    "    <head>\n" +
                    "        <meta charset=\"UTF-8\" />\n" +
                    "    </head>\n" +
                    "    <p>您好，验证码为<span style=\"font-size: 2em;font-weight: bold\">"+ code +"</span>，请在壹付app上输入此验证码，有效期为15分钟。如果本封邮件非您本人触发，请忽略。</p>\n" +
                    "</html>");
            String responseStr = JSON.toJSONString(client.getAcsResponse(request));
            JSONObject result = JSON.parseObject(responseStr);
            return result.get("Code") == null;
        } catch (ServerException e) {
            e.printStackTrace();
            return false;
        }
        catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }
}
